package com.itheima.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itheima.Result.Result;
import com.itheima.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class LoginCheckInterceptor implements HandlerInterceptor {
    private final JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        //过滤路径在配置拦截器中处理
        //获取请求头token，判断是否存在，如果存在且正确，则放行，否则拦截
        String token = request.getHeader("token");

        if(StringUtils.hasLength(token)){
            try {
                jwtUtils.parseJWT(token);
                return true;
            } catch (Exception e) {
                log.info("令牌解析失败!");
                Result responseResult = Result.error("未登录");
                //把Result对象转换为JSON格式字符串 (fastjson是阿里巴巴提供的用于实现对象和json的转换工具类)
                String json = JSONObject.toJSONString(responseResult);
                //设置响应头
                response.setContentType("application/json;charset=utf-8");
                //响应
                response.getWriter().write(json);
                return false;
            }
        }

        return false;
    }

}
